import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

public class 定时任务 {
    public static void main(String[] args) {
        ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);

        // 每隔2秒执行一次（固定速率）
        scheduler.scheduleAtFixedRate(() -> {
            System.out.println("Fixed Rate Task - " + new Date());
            try {
                Thread.sleep(1000); // 模拟任务耗时1秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, 0, 2, TimeUnit.SECONDS);

        // 每次执行完后等2秒再执行下一次（固定延迟）
        scheduler.scheduleWithFixedDelay(() -> {
            System.out.println("Fixed Delay Task - " + new Date());
            try {
                Thread.sleep(1500); // 模拟任务耗时1.5秒
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
        }, 0, 2, TimeUnit.SECONDS);
        // 为了演示，10秒后关闭调度器
        scheduler.schedule(() -> {
            scheduler.shutdown();
            System.out.println("Scheduler shutdown.");
        }, 10, TimeUnit.SECONDS);
    }
}